// pages/me/index.js
// pages/me/index.js
new Vue({
    el: '#me_app',
    delimiters: ['[[', ']]'], // 明确设置Vue.js的模板分隔符
    data: {
        userInfo: null, // 用于存储从URL解析的用户信息
        currentTab: 'pending', // 'pending' 或 'paid'
        allOrders: [],
        pendingOrders: [],
        paidOrders: [],
        refundedOrders: []
    },
    mounted() {
        // 1. 尝试从 localStorage 读取用户信息
        const storedUserInfo = localStorage.getItem('wechatUserInfo');
        if (storedUserInfo) {
            this.userInfo = JSON.parse(storedUserInfo);
            console.log('从 localStorage 获取用户信息:', this.userInfo);
        }

        // 2. 如果 localStorage 中没有，或者需要更新，则从 URL 参数解析
        const userInfoFromUrl = this.parseUserInfoFromUrl();
        if (userInfoFromUrl) {
            this.userInfo = userInfoFromUrl;
            localStorage.setItem('wechatUserInfo', JSON.stringify(userInfoFromUrl));
            console.log('从 URL 获取并保存用户信息:', this.userInfo);
            // 清除URL中的用户信息参数，保持URL整洁
            window.history.replaceState({}, document.title, window.location.pathname);
        }

        if (!this.userInfo) {
            console.log('未检测到用户信息，请点击登录按钮进行微信授权。');
        } else {
            this.fetchOrders(); // 用户登录后获取订单
        }

        // 3. 解析URL中的tab参数，如果存在则设置currentTab
        const params = new URLSearchParams(window.location.search);
        if (params.has('tab')) {
            const tabFromUrl = params.get('tab');
            if (['pending', 'paid', 'refunded'].includes(tabFromUrl)) {
                this.currentTab = tabFromUrl;
                console.log(`从 URL 设置初始 Tab: ${this.currentTab}`);
            }
            // 清除URL中的tab参数，保持URL整洁
            window.history.replaceState({}, document.title, window.location.pathname.split('?')[0]);
        }

        // 监听 localStorage 变化，实现多页面登录状态同步
        window.addEventListener('storage', this.handleStorageChange);
    },
    beforeDestroy() {
        // 移除事件监听器，防止内存泄漏
        window.removeEventListener('storage', this.handleStorageChange);
    },
    methods: {
        handleStorageChange(event) {
            if (event.key === 'wechatUserInfo') {
                const newUserInfo = event.newValue ? JSON.parse(event.newValue) : null;
                if (JSON.stringify(this.userInfo) !== JSON.stringify(newUserInfo)) {
                    this.userInfo = newUserInfo;
                    console.log('Storage 变化，更新用户信息:', this.userInfo);
                    if (this.userInfo) {
                        this.fetchOrders(); // 用户登录后获取订单
                    } else {
                        this.allOrders = [];
                        this.pendingOrders = [];
                        this.paidOrders = [];
                        this.refundedOrders = [];
                    }
                }
            }
        },
        parseUserInfoFromUrl() {
            const params = new URLSearchParams(window.location.search);
            if (params.has('openid')) {
                const userInfo = {
                    openid: params.get('openid'),
                    nickname: decodeURIComponent(params.get('nickname') || ''),
                    headimgurl: params.get('headimgurl'),
                    sex: params.get('sex'),
                    province: decodeURIComponent(params.get('province') || ''),
                    city: decodeURIComponent(params.get('city') || ''),
                    country: decodeURIComponent(params.get('country') || '')
                };
                return userInfo;
            }
            return null;
        },
        redirectToWechatAuth() {
            const redirectUri = encodeURIComponent(window.location.origin + '/rzwl/wechat/oauth_callback');
            const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${window.WECHAT_APP_ID}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_userinfo&state=me#wechat_redirect`;
            window.location.href = authUrl;
        },
        clearCacheAndReload() {
            if (confirm('确定要清理缓存并强制刷新页面吗？这可能解决一些显示问题。')) {
                window.location.reload(true);
            }
        },
        logout() {
            if (confirm('确定要登出吗？')) {
                localStorage.removeItem('wechatUserInfo');
                this.userInfo = null; // 清除当前Vue实例中的用户信息
                window.location.reload(true); // 强制刷新页面以反映登出状态
            }
        },
        fetchOrders() {
            if (!this.userInfo || !this.userInfo.openid) {
                console.warn('无法获取订单：用户未登录或OpenID缺失。');
                return;
            }
            axios.get(`/rzwl/api/orders/${this.userInfo.openid}`)
                .then(response => {
                    this.allOrders = response.data;
                    this.pendingOrders = this.allOrders.filter(order => order.status === 'unpaid');
                    this.paidOrders = this.allOrders.filter(order => order.status === 'paid');
                    this.refundedOrders = this.allOrders.filter(order => order.status === 'refunded');
                })
                .catch(error => {
                    console.error('获取订单失败:', error);
                    this.allOrders = [];
                    this.pendingOrders = [];
                    this.paidOrders = [];
                });
        },
        goToPayPage(orderId) {
            window.location.href = `/rzwl/pay?order_id=${orderId}`;
        }
    },
    watch: {
        currentTab(newTab, oldTab) {
            console.log(`Tab changed from ${oldTab} to ${newTab}`); // 添加调试信息
            // 当 currentTab 变化时，重新过滤订单
            if (this.allOrders.length > 0) {
                this.pendingOrders = this.allOrders.filter(order => order.status === 'unpaid');
                this.paidOrders = this.allOrders.filter(order => order.status === 'paid');
                this.refundedOrders = this.allOrders.filter(order => order.status === 'refunded');
            }
        }
    }
});
